
package org.itboys.mobile.util.apk;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.itboys.mobile.entity.mongo.SundayApkInfo;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;



/**
 * 作者：jiangxiong
 * 日期：2016年4月6日
 * 联系方式 ：empty90911@126.com
 * 描述：app上传相关工具
 */

public class ApkUtil {
	
	private static final Namespace NS = Namespace.getNamespace("http://schemas.android.com/apk/res/android");
	
	public static SundayApkInfo getApkInfo(String apkPath){
		SundayApkInfo apkInfo = new SundayApkInfo();
		SAXBuilder builder = new SAXBuilder();
		Document document = null;
		try{
			document = builder.build(getXmlInputStream(apkPath));
		}catch (Exception e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();//跟节点-->manifest
		apkInfo.setVersionCode(Integer.valueOf(root.getAttributeValue("versionCode",NS)));
		apkInfo.setVersionName(root.getAttributeValue("versionName", NS));
		apkInfo.setApkPackage(root.getAttributeValue("package"));
		Element elemUseSdk = root.getChild("uses-sdk");//子节点-->uses-sdk
		apkInfo.setMinSdkVersion(elemUseSdk.getAttributeValue("minSdkVersion", NS));
		
		Element application = root.getChild("application");//子节点-->uses-sdk
		apkInfo.setApkName(application.getAttributeValue("label", NS));
		System.out.println(apkInfo.toString());
		return apkInfo;
	}
	


	private static InputStream getXmlInputStream(String apkPath) {
		InputStream inputStream = null;
		InputStream xmlInputStream = null;
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(apkPath);
			ZipEntry zipEntry = new ZipEntry("AndroidManifest.xml");
			inputStream = zipFile.getInputStream(zipEntry);
			AXMLPrinter xmlPrinter = new AXMLPrinter();
			xmlPrinter.startPrinf(inputStream);
			xmlInputStream = new ByteArrayInputStream(xmlPrinter.getBuf().toString().getBytes("UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
			try {
				inputStream.close();
				zipFile.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return xmlInputStream;
	}
	public static void main(String[] args) {
		getApkInfo("C:/Users/Administrator/Desktop/app-release.apk");
	}
}

